import type { Directive, DirectiveBinding } from 'vue'
import { VNode } from 'vue/types/umd'
const nodeList: any[] = []
const ctx: string = '@@clickoutsideContext'

let startClick: MouseEvent | null = null
let seed: number = 0

window.addEventListener('mousedown', e => (startClick = e))
window.addEventListener('mouseup', e => {
  nodeList.forEach(node => node[ctx].documentHandler(e, startClick))
})

function createDocumentHandler(el: any, binding: DirectiveBinding<any>, vnode: VNode) {
  return function (mouseup: MouseEvent, mousedown: MouseEvent) {
    const vnodeContext = vnode.context as any
    if (
      !vnode ||
      !vnode.context ||
      !mouseup.target ||
      !mousedown.target ||
      el.contains(mouseup.target) ||
      el.contains(mousedown.target) ||
      el === mouseup.target ||
      (vnodeContext.popperElm &&
        (vnodeContext.popperElm.contains(mouseup.target) ||
          vnodeContext.popperElm.contains(mousedown.target)))
    )
      return

    if (binding.expression && el[ctx].methodName && vnodeContext[el[ctx].methodName]) {
      vnodeContext[el[ctx].methodName]()
    } else {
      el[ctx].bindingFn && el[ctx].bindingFn()
    }
  }
}

const clickoutside: Directive = {
  bind(el, binding, vnode) {
    nodeList.push(el)
    const id = seed++
    el[ctx] = {
      id,
      documentHandler: createDocumentHandler(el, binding, vnode),
      methodName: binding.expression,
      bindingFn: binding.value
    }
  },
  update(el, binding, vnode) {
    el[ctx].documentHandler = createDocumentHandler(el, binding, vnode)
    el[ctx].methodName = binding.expression
    el[ctx].bindingFn = binding.value
  },
  unbind(el) {
    const len = nodeList.length
    for (let i = 0; i < len; i++) {
      if (nodeList[i][ctx].id === el[ctx].id) {
        nodeList.splice(i, 1)
        break
      }
    }
    delete el[ctx]
  }
}
export default clickoutside
